<?php
/**
 * 余额积分
 * Created by PhpStorm.
 * User: lirui
 * Date: 2020/2/5
 * Time: 上午11:34
 */

namespace App\Services;

use App\Models\CreditLog;
use App\Models\Order;
use App\Models\RechargeLog;
use App\Models\User;
use App\Models\UserBill;
use Illuminate\Support\Facades\DB;

class BalanceService extends BaseService
{
    /**
     * 充值退款
     * @param RechargeLog $rechargeLog
     * @return boolean | string
     */
    public static function refundRecharge(RechargeLog $rechargeLog)
    {
        if ($rechargeLog->state != 1) {
            return self::ierror(-1, '未充值成功不能退款！');
        }

        $user = User::find($rechargeLog->uid);
        $credit = $user->credit;
        $balance = $user->balance;
        $giveBalance = $user->give_balance;

        if ($rechargeLog->recharge_credit) {
            $credit -= $rechargeLog->recharge_credit;
        }
        if ($rechargeLog->recharge_money) {
            $balance -= $rechargeLog->recharge_money;
        }
        if ($rechargeLog->give_money) {
            $giveBalance -= $rechargeLog->give_money;
        }
        if ($rechargeLog->give_credit) {
            $credit -= $rechargeLog->give_credit;
        }

        $balance = max(0, $balance);
        $giveBalance = max(0, $giveBalance);
        $credit = max(0, $credit);

        $user->balance = $balance;
        $user->give_balance = $giveBalance;
        $user->credit = $credit;
        $user->save();

        $givePresentcredit = 0;
        if ($rechargeLog->type == 1) {
            $num = $rechargeLog->recharge_money;
            $presentcredit = $user->balance;
            $givePresentcredit = $user->give_balance;
            $text = '余额';
        } elseif ($rechargeLog->type == 2) {
            $num = $rechargeLog->recharge_credit;
            $presentcredit = $user->credit;
            $text = '积分';
        }

        $text = "退款退{$text}";

        $rechargeLog->state = 2;
        $rechargeLog->save();

        //插入余额明细
        self::addCreditLog(21, $rechargeLog->uid,
            $rechargeLog->type,
            -$num,
            $presentcredit,
            $text,
            -$rechargeLog->give_money,
            -$rechargeLog->give_credit,
           1,
            $givePresentcredit
        );

        //记录用户账单
        UserBill::expend(
            '余额充值退款扣余额', $user->id, 'balance', 'refund_recharge', $num, $rechargeLog->id, $presentcredit, $text
        );

        return true;
    }

    /**
     * @param $logType
     * @param $uid
     * @param $type
     * @param $num
     * @param $presentcredit
     * @param string $remark
     * @param int $giveMoney
     * @param int $giveCredit
     * @param int $operator
     * @param int $givePresentcredit
     * @param int $orderId
     */
    public static function addCreditLog($logType, $uid, $type, $num, $presentcredit, $remark = '', $giveMoney = 0, $giveCredit = 0, $operator = 0, $givePresentcredit = 0, $orderId = 0)
    {
        $data = [
            'log_type' => (int)$logType,
            'uid' => (int)$uid,
            'type' => (int)$type,
            'order_id' => (int)$orderId,
            'num' =>  (float)$num,
            'give_money' => (float)$giveMoney,
            'give_credit' =>  (float)$giveCredit,
            'presentcredit' =>  (float)$presentcredit,
            'give_presentcredit' =>  (float)$givePresentcredit,
            'remark' => (string)$remark,
            'operator' => (int)$operator,
        ];

        $log = new CreditLog();
        $log->fill($data)->save();
        //记录用户账单
        switch ($type) {
            case 1:
                $category = 'balance';
                break;
            case 2:
                $category = 'credit';
                break;
        }
        if ($num > 0) {
            $pm = 1;
        } else {
            $pm = 0;
        }

        $title = CreditLog::$logType[$logType];
        //记录用户账单
        UserBill::expend(
            $title, $uid, $category, 'credit_log_type_' . $logType, abs($num), $log->id, $presentcredit, $remark, 1, $pm
        );

    }

    /**
     * 系统赠送余额
     * @param $user User
     * @param $rechargeMoney
     * @param $giveMoney
     * @param $giveCredit
     * @param $from
     * @param string $remark
     * @param int $operator
     * @return bool|mixed
     * @throws
     */
    public static function systemGiveBalance($user, $rechargeMoney, $giveMoney, $giveCredit, $from, $remark = '', $operator = 0){
        DB::beginTransaction();
        if (!$user || !$rechargeMoney) {
            return self::ierror(-1, '充值余额参数错误');
        }

        $credit = $user->credit;
        $balance = $user->balance;
        $giveBalance = $user->give_balance;

        if ($giveCredit) {
            $credit += $giveCredit;
        }
        if ($rechargeMoney) {
            $balance += $rechargeMoney;
        }
        if ($giveMoney) {
            $giveBalance += $giveMoney;
        }

        $balance = max(0, $balance);
        $giveBalance = max(0, $giveBalance);
        $credit = max(0, $credit);

        $user->balance = $balance;
        $user->give_balance = $giveBalance;
        $user->credit = $credit;
        $ret = $user->saveOrFail();

        if (!$ret) {
            DB::rollBack();
            return self::ierror(-1, '更新用户充值数据失败');
        }

        //插入明细日志
        self::addCreditLog($from, $user->id,
            1,
            $rechargeMoney,
            $user->balance,
            $remark,
            $giveMoney,
            $giveCredit,
            $operator,
            $user->give_balance
        );

        DB::commit();
        return true;
    }

    /**
     * 充值余额
     * @param $user User 用户
     * @param $orderId int 订单id
     * @param $rechargeMoney float 充值金额
     * @param $giveMoney float 赠送金额
     * @param $giveCredit float 赠送积分
     * @param $from int 事件
     * @param $remark string 备注
     * @param $operator int 后台操作员
     * @return bool
     * @throws
     */
    public static function rechargeBalance($user, $orderId, $rechargeMoney, $giveMoney, $giveCredit, $from, $remark = '', $operator = 0)
    {
        DB::beginTransaction();
        if (!$user || !$rechargeMoney) {
            return self::ierror(-1, '充值余额参数错误');
        }

        $credit = $user->credit;
        $balance = $user->balance;
        $giveBalance = $user->give_balance;

        if ($giveCredit) {
            $credit += $giveCredit;
        }
        if ($rechargeMoney) {
            $balance += $rechargeMoney;
        }
        if ($giveMoney) {
            $giveBalance += $giveMoney;
        }

        $balance = max(0, $balance);
        $giveBalance = max(0, $giveBalance);
        $credit = max(0, $credit);

        $user->balance = $balance;
        $user->give_balance = $giveBalance;
        $user->credit = $credit;
        $ret = $user->saveOrFail();

        if (!$ret) {
            DB::rollBack();
            return self::ierror(-1, '更新用户充值数据失败');
        }

        //插入充值日志
        $rechargeLog = new RechargeLog();
        $data = [
            'uid' => $user->id,
            'order_id' => $orderId,
            'recharge_money' => $rechargeMoney,
            'give_money' => $giveMoney,
            'give_credit' => $giveCredit,
            'type' => 1,
            'from' => $from,
            'state' => 1,
            'remark' => $remark,
            'operator' => $operator,
        ];
        $rechargeLog->fill($data)->saveOrFail();

        //插入明细日志
        self::addCreditLog($from, $user->id,
            1,
            $rechargeMoney,
            $user->balance,
            $remark,
            $giveMoney,
            $giveCredit,
            $operator,
            $user->give_balance
        );

        DB::commit();
        return true;
    }

    /**
     * 创建用户充值订单
     * @param $user User 用户信息
     * @param $money float 充值金额
     * @return string | Order
     * @throws
     */
    public static function createRechargeOrder($user, $money)
    {
        if ($money <= 0) {
            return self::ierror(-1, '充值金额错误');
        }

        $orderInfo = [
            'uid' => $user['id'],
            'type' => 5,
            'order_id' => OrderService::getNewOrderId(),
            'pay_price' => $money,
            'paid' => 0,
            'add_time' => time(),
        ];

        $key = md5($orderInfo['uid'] . '_5_' . $orderInfo['order_id']);
        $orderInfo['unique'] = $key;

        $order = new Order();
        $saveRet = $order->fill($orderInfo)->saveOrFail();
        $rechargeGive = self::getRechargeGive($money);

        //插入充值日志
        $rechargeLog = new RechargeLog();

        $data = [
            'uid' => $user->id,
            'order_id' => $order->id,
            'recharge_money' => $money,
            'give_money' => $rechargeGive['give_money'],
            'give_credit' => $rechargeGive['give_credit'],
            'type' => 1,
            'from' => 1,
            'state' => 0,
        ];
        $rechargeLog->fill($data)->saveOrFail();

        if (!$saveRet) {
            return self::ierror(-1, '订单生成失败5!');
        }

        return $order;
    }

    /**
     * 获取充值余额赠送
     * @param $money
     * @return array
     */
    public static function getRechargeGive($money)
    {
        $result = [
            'give_credit' => 0,//赠送积分
            'give_money' => 0,//赠送余额
        ];

        $config = ConfigService::getSysValueByType(18);

        if (!$config) {
            return $result;
        }

        foreach ($config as $item) {
            if ($item['enough'] == $money) {
                $result['give_money'] = $item['give'];
            }
        }

        return $result;
    }

    /**
     * 余额充值成功订单回调
     * @param $order
     * @return bool|void
     * @throws \Throwable
     */
    public static function rechargeBalanceSuccessNotify($order)
    {
        DB::beginTransaction();

        $rechargeLog = RechargeLog::where('order_id', $order->id)->first();

        if (!$rechargeLog) {
            exception('充值订单不存在');
        }

        $user = User::find($rechargeLog->uid);

        if (!$user) {
            exception('充值用户不存在');
        }

        $credit = $user->credit;
        $balance = $user->balance;
        $giveBalance = $user->give_balance;

        if ($rechargeLog->give_credit) {
            $credit += $rechargeLog->give_credit;
        }
        if ($rechargeLog->recharge_money) {
            $balance += $rechargeLog->recharge_money;
        }
        if ($rechargeLog->give_money) {
            $giveBalance += $rechargeLog->give_money;
        }

        $balance = max(0, $balance);
        $giveBalance = max(0, $giveBalance);
        $credit = max(0, $credit);

        $user->balance = $balance;
        $user->give_balance = $giveBalance;
        $user->credit = $credit;
        $user->recharge_money = $user->recharge_money + $rechargeLog->recharge_money;

        $ret = $user->saveOrFail();

        if (!$ret) {
            DB::rollBack();
            return self::ierror(-1, '更新用户充值数据失败');
        }

        $rechargeLog->state = 1;
        $rechargeLog->save();

        //插入明细日志
        self::addCreditLog($rechargeLog->from, $user->id,
            1,
            $rechargeLog->recharge_money,
            $user->balance,
            '用户线上充值',
            $rechargeLog->give_money,
            $rechargeLog->give_credit,
            0,
            $user->give_balance
        );

        DB::commit();
        return true;
    }
}